package com.jcnet.bizaia.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jcnet.bizaia.App;
import com.jcnet.bizaia.R;
import com.jcnet.bizaia.VodDetailActivity;
import com.jcnet.bizaia.adapter.MainVoiceDeatalAdapter;
import com.jcnet.bizaia.bean.VoiceDetailBean;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.HeadViewPageView;
import com.jcnet.bizaia.xstream.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView.OnActionClickListener;


/**
 * @author chenguandong
 * @category  主页下 音乐分类下的详细
 *
 */
@SuppressLint("ValidFragment")
public class VoiceDetailFragmentForSearch extends Fragment implements OnItemClickListener {

	
	private List<VoiceDetailBean> mainInfoBeans;

	private List<VoiceDetailBean>tempInfoBeans;

	private ActionSlideExpandableListView listView;

	private View bottomView;  //底部加载更多按钮

	private View headViewPageView;

	private View emptyView;     //数据为空

	private View noNetWorkView;  //没有网络\


	private View firstLodingView;  //没有网络\

	private MainVoiceDeatalAdapter infoAdapter;

	private int nowPageSize = 1;

	private int category =2;

	private ACache aCache;

	private String HTTP_REQUEST =  App.HTTP_PATH+"sud_showSoundList.action?";

	private RequestParams params;
	
	private int allPapeSize;

	private boolean mLastItemVisible;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		aCache = ACache.get(getActivity());

		View view = View.inflate(getActivity(), R.layout.voice_detail,null);

		bottomView = View.inflate(getActivity(), R.layout.comm_foot_view, null);

		firstLodingView = View.inflate(getActivity(), R.layout.init_locad_view, null);

		headViewPageView = new HeadViewPageView(getActivity(), category);

		listView = (ActionSlideExpandableListView)view.findViewById(R.id.commListViewBase);

		emptyView = View.inflate(getActivity(), R.layout.list_empty_no_data, null);
		
		noNetWorkView = View.inflate(getActivity(), R.layout.list_no_network, null);

		initListView();
		System.out.println("onCreateView__________________");
		return view;
	}

	public static VoiceDetailFragmentForSearch newInstance(RequestParams params) {
		VoiceDetailFragmentForSearch fragment = new VoiceDetailFragmentForSearch();
		fragment.params = params;
		return fragment;
	}


	public VoiceDetailFragmentForSearch() {
		super();
		// TODO Auto-generated constructor stub
	}


	public VoiceDetailFragmentForSearch(RequestParams params) {
		super();
		this.params = params;
	}


	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		if(isVisibleToUser){
			System.out.println("onCreateView__________________");
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	private void initListView() {
		// TODO Auto-generated method stub

		mainInfoBeans = new ArrayList<VoiceDetailBean>();

		tempInfoBeans = new ArrayList<VoiceDetailBean>();


		infoAdapter = new MainVoiceDeatalAdapter(getActivity(), mainInfoBeans);


		listView.setOnItemClickListener(this);

		listView.setItemActionListener(new OnActionClickListener() {
			
			@Override
			public void onClick(View listView, View buttonview, int position) {
				// TODO Auto-generated method stub
				String actionName = "";
				if(buttonview.getId()==R.id.buttonPlay) {
					actionName = "buttonA";
					Toast.makeText(getActivity(), "button click", 0).show();
				} else {
					actionName = "ButtonB";
				}
			}
		}, 
		R.id.buttonPlay,
		R.id.buttonDownload,
		R.id.buttonStart,
		R.id.buttonTalk,
		R.id.buttonShare
		);
		
		/**
		 * 下拉刷新需要做的事情
		 * if(Toolkit.isAvaliable(getActivity())){
					if(mainInfoBeans!=null){
						mainInfoBeans.clear();
					}
					nowPageSize = 1;
					sendHttp(nowPageSize);
				}else{
					
					Toast.makeText(getActivity(), getString(R.string.noNetWork), 0).show();
					refreshView.onRefreshComplete();
					
				}
		 */

		/**
		 * 滚动到底部加载更多需要做的事情
		 * 
				// TODO Auto-generated method stub
				
				System.out.println("??????????????");
				System.out.println("nowPageSize"+nowPageSize);
				System.out.println("allPapeSize"+allPapeSize);
				
				if(nowPageSize==allPapeSize){
					bottomView.setVisibility(View.GONE);   //到达底部没有更多数据
					Toast.makeText(getActivity(), getString(R.string.noData), 0).show();
				}else{
					bottomView.setVisibility(View.VISIBLE);  //到达底部还有更多数据
					nowPageSize = nowPageSize+1;
					sendHttp(nowPageSize);
				}

			
		 */

		listView.setAdapter(infoAdapter);
		listView.setOnItemClickListener(this);
		listView.setEmptyView(firstLodingView);
		//simpleListView.addHeaderView(headViewPageView);
		listView.addFooterView(bottomView);
		sendHttp(nowPageSize);
		
		
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE  && mLastItemVisible) {
					Toast.makeText(getActivity(), "滚动了底部", 0).show();
					
					System.out.println("??????????????");
					System.out.println("nowPageSize"+nowPageSize);
					System.out.println("allPapeSize"+allPapeSize);
					
					if(nowPageSize==allPapeSize){
						bottomView.setVisibility(View.GONE);   //到达底部没有更多数据
						Toast.makeText(getActivity(), getString(R.string.noData), 0).show();
					}else{
						bottomView.setVisibility(View.VISIBLE);  //到达底部还有更多数据
						nowPageSize = nowPageSize+1;
						sendHttp(nowPageSize);
					}

				}
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
					mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
					
					System.out.println("mLastItemVisible="+mLastItemVisible);
					
					
			
			}
		});
		
		
	

	}

	public void sendHttp(int page){
		
		
		/**
		 参数名称
				参数类型
				说明
				languageNum
				int
				语言种类：1：中文2：英文3：日文
				datelineNum
				date
				时间日期检索（搜索全部时赋值null/-1等均可）
				title
				string
				音频标题
				cidNum
				int
				分类id检索（默认全部时赋值-1）
				pageNum
				int
				当前第几页（默认第一页）
				pageSizeNum
				int
				当前分页显示条数（默认20条）

		 */
		
		params.put("pageNum", page+"");
		
		//params.put("pageSizeNum",20);   //默认不传20 
		

		if(Toolkit.isAvaliable(getActivity())){

			new AsyncHttpClient().post(HTTP_REQUEST,params ,new AsyncHttpResponseHandler(){

				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
					
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub\

					super.onSuccess(arg0, arg1, arg2);

					setListData(new String(arg2));
					
					
				}


				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					bottomView.setVisibility(View.GONE);
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					Toast.makeText(getActivity(), getString(R.string.serverError), 0).show();
					super.onFailure(arg0, arg1, arg2, arg3);
				}
			});
		}else{

			listView.setEmptyView(noNetWorkView);


			firstLodingView.setVisibility(View.GONE);

			String requestString = aCache.getAsJSONObject(HTTP_REQUEST+params).toString();
			
			if(requestString!=null){
				
				setListData(requestString);
			}
			
			
			Toast.makeText(getActivity(), getString(R.string.noNetWork), 1).show();

		}
	}
	
	
	private void setListData(String arg2){
		

		
		String requestString = arg2;

		AllVoidRequestData requestBeanRequest = new AllVoidRequestData();

		//System.out.println("byte:"+new String(arg2));

		if(requestString!=null){
			
			aCache.put(HTTP_REQUEST+params, requestString,App.CACHE_TIME_DAY);
			
			requestBeanRequest = new Gson().fromJson(requestString, new TypeToken<AllVoidRequestData>(){}.getType());

			
			allPapeSize = requestBeanRequest.getPagsum();
			
			if(requestBeanRequest.getState()==200){

				firstLodingView.setVisibility(View.GONE);
				
				tempInfoBeans = null;
				
				tempInfoBeans = requestBeanRequest.getObjlistJson();
				
				if(!tempInfoBeans.isEmpty()||tempInfoBeans!=null){
					
					if(tempInfoBeans.isEmpty()||mainInfoBeans.size()<20){   //当本页的


						bottomView.setVisibility(View.GONE);

					}
					
					if(!tempInfoBeans.isEmpty()){

						mainInfoBeans.addAll(tempInfoBeans);

						infoAdapter.count = mainInfoBeans.size();

						infoAdapter.notifyDataSetChanged();
					}
				}


				//如果得到的内容总数为空的话显示没有数据的页面,同时隐藏foot界面
				if(mainInfoBeans.isEmpty()){
					listView.setEmptyView(emptyView);
					bottomView.setVisibility(View.GONE);
				}


			}

		}

	}
	
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		String source = "http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8";
		//Intent intent = new Intent(getActivity(), VideoViewPlayingActivity.class);
		Intent intent = new Intent(getActivity(), VodDetailActivity.class);
		
		
		intent.setData(Uri.parse(source));
		
		
		startActivity(intent);	

	}

	
	class AllVoidRequestData{
		private  int state;
		private  String message;
		private int pagsum;
		private  List<VoiceDetailBean> objlistJson;
		public int getState() {
			return state;
		}
		public void setState(int state) {
			this.state = state;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public int getPagsum() {
			return pagsum;
		}
		public void setPagsum(int pagsum) {
			this.pagsum = pagsum;
		}
		public List<VoiceDetailBean> getObjlistJson() {
			return objlistJson;
		}
		public void setObjlistJson(List<VoiceDetailBean> objlistJson) {
			this.objlistJson = objlistJson;
		}
	
		
		
	}

}
